export class MessageEncryptor {
  static MessageEncryptorContentPrefix = "[MXENC]:";
  static IsEncry = false; // 是否启用加密，默认 false

  /**
   * 压缩连续空格（0020）
   * @param {string} unicodeStr Unicode 字符串
   * @returns {string} 压缩后的字符串
   */
  static compressSpacesWithCount(unicodeStr: string): string {
    return unicodeStr.replace(/(0020)+/g, match => {
      const spaceCount = match.length / 4;
      return `[${spaceCount}]`;
    });
  }

  /**
   * 解压缩连续空格
   * @param {string} compressedStr 压缩后的字符串
   * @returns {string} 解压缩后的字符串
   */
  static decompressSpaces(compressedStr: string): string {
    return compressedStr.replace(/\[(\d+)]/g, (_, group1) => {
      const spaceCount = parseInt(group1, 10);
      return "0020".repeat(spaceCount);
    });
  }

  /**
   * 加密字符串（转为 Unicode 编码并压缩空格）
   * @param {string} originalMessage 原始字符串
   * @returns {string} 加密后的字符串
   */
  static encrypt(originalMessage: string): string {
    if (!this.IsEncry) {
      return originalMessage;
    }

    let unicodeString = "";
    for (let i = 0; i < originalMessage.length; i++) {
      const code = originalMessage.charCodeAt(i);
      unicodeString += code.toString(16).padStart(4, '0');
    }

    return this.compressSpacesWithCount(unicodeString).toUpperCase();
  }

  /**
   * 解密字符串（还原 Unicode 编码）
   * @param {string} encryptedMessage 加密后的字符串
   * @returns {string} 解密后的字符串
   */
  static decrypt(encryptedMessage: string): string {
    const decompressed = this.decompressSpaces(encryptedMessage);
    let str = "";

    // 每 4 个字符为一组，解析为 Unicode 码点
    for (let i = 0; i < decompressed.length; i += 4) {
      const hex = decompressed.substring(i, i + 4);
      const code = parseInt(hex, 16);
      str += String.fromCharCode(code);
    }

    return str;
  }
}

// 示例用法
// MessageEncryptor.IsEncry = true; // 启用加密
//
// const originalText = "刚刚登录";
// const encrypted = MessageEncryptor.encrypt(originalText);
// console.log("加密后:", encrypted);
//
// const decrypted = MessageEncryptor.decrypt(encrypted);
// console.log("解密后:", decrypted);
